package io.renren.newpaypay;

import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PayGatewayUtil {





	
	public static String post(JSONObject jsonObj ,String url,String key){

		try {

			String tradeId = "payGateway";
			String tradeData = jsonObj.toString();
			String md5Src = tradeData + "&" + key;  //md5源串

			// {"merId":"62117401","orderId":"1586863620755","goods":"巧克力100136","amount":"0.03","expTime":"","notifyUrl":"http://xxx","pageUrl":"http://xxx","reserve":"保留123","extendInfo":"扩展信息","payMode":"01","payBankId":"CCB","creditType":"2","userId":"000001","clientIp":"127.0.0.1"}&7461b450-e7a8-4993-97ed-5eb33e051222
			byte[] bTradeSign = Md5.md5(md5Src.getBytes("UTF-8")); //md5加密
			String tradeSign = ByteUtil.bytes2HexStr(bTradeSign);//字节转字符,如0x1234AB -> “1234AB”

			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("tradeId",tradeId));
			nvps.add(new BasicNameValuePair("ver","1.0"));
			nvps.add(new BasicNameValuePair("tradeData",tradeData));
			nvps.add(new BasicNameValuePair("tradeSign",tradeSign));
			

			String response = HttpClientUtils.doPost(url,nvps,HTTP.UTF_8).trim();
			System.out.println("response: " + response);

//			response: {"backData":{"payUrl":"http://client.newpingon.com/c/qr.do?a=0D5F07817B704C4061A87B5CF2FA4969"},"backSign":"BC6BF01975EB78A12965839EE4E09CAA","info":"交易成功","status":"0000"}
//			md5Src: {"payUrl":"http://client.newpingon.com/c/qr.do?a=0D5F07817B704C4061A87B5CF2FA4969"}&7461b450-e7a8-4993-97ed-5eb33e051222

			//返回数据处理
			JSONObject jsonResp = JSONObject.fromObject(response);
			String backSign = jsonResp.getString("backSign");
			if((backSign == null)||(backSign.length() == 0)){
				return "";
			}
			
			//有数据
			JSONObject backData = jsonResp.getJSONObject("backData");
			md5Src = backData + "&" + key;
			System.out.println("md5Src: " + md5Src);
			boolean check = Md5.md5Verify(md5Src, backSign);
			if(!check){
				return "";
			}
			return backData.getString("payUrl");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	




	
}


